package com.wis.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.umeng.analytics.MobclickAgent;
import com.wis.BuildConfig;
import com.wis.R;
import com.wis.application.WisApplication;
import com.wis.face.WisUtil;
import com.wis.util.SingleMediaScanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;

import face.entity.FaceFeaturePoint;
import face.entity.FaceModel;

import static android.os.Environment.getExternalStorageDirectory;

@SuppressLint("SdCardPath")
public class CompareActivity extends Activity implements View.OnClickListener {

    private WisApplication application;

    private Button leftLocalBtn, leftTakeBtn, rightLocalBtn, rightTakeBtn, compareBtn;
    private ImageView leftImageView, rightImageView;
    private TextView resultView;
    private ProgressBar progressBar;
    private ActionBar actionBar;

    private File tempFile = new File(getExternalStorageDirectory(),
            getPhotoFileName());

    private String localFileLeft="";
    private  String localFileRight="";
    private File leftTempFile=new File(getExternalStorageDirectory(),
            getPhotoFileName());
    private  File rightTempFile=new File(getExternalStorageDirectory(),
            getPhotoFileName());

    private int photoDirection;
    private static final int PHOTO_LEFT = 1;// 左侧
    private static final int PHOTO_RIGHT = 2;// 右侧

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果



    private Handler mHandler;
    private final static int COMPARE = 1;

    private float score=0.0f;

    private Uri leftPhotoUri;
    private Uri rightPhotoUri;
    private Bitmap leftPhoto;
    private Bitmap rightPhoto;

    private Uri uritempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compare);
        application = (WisApplication) getApplication();
        actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        initView();
        // 比对，更新UI
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case COMPARE:
//                        Log.i("face", "score= start");
//                        String fileName1 = "/sdcard/wis/images/1.jpg";
//                        String fileName2 = "/sdcard/wis/images/2.jpg";
//                        //compare 2 faces in 2 picture
//                        Log.e("compare", "1");
//                        float score = application.getWisMobile().compare2Image(fileName1, fileName2);
//                        Log.e("compare", "2");
//                        Log.i("face", "score=" + score);
//
//                        progressBar.setVisibility(View.GONE);
//                        resultView.setText("比对结果：" + (score * 100) + "%");
//                        Toast.makeText(CompareActivity.this, "比对结果：" + (score * 100) + "%", Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void initView() {
        leftImageView = (ImageView) findViewById(R.id.left_img);
        rightImageView = (ImageView) findViewById(R.id.right_img);

        leftLocalBtn = (Button) findViewById(R.id.left_local);
        leftTakeBtn = (Button) findViewById(R.id.left_take);
        rightLocalBtn = (Button) findViewById(R.id.right_local);
        rightTakeBtn = (Button) findViewById(R.id.right_take);

        leftLocalBtn.setOnClickListener(this);
        leftTakeBtn.setOnClickListener(this);
        rightLocalBtn.setOnClickListener(this);
        rightTakeBtn.setOnClickListener(this);

        compareBtn = (Button) findViewById(R.id.compare);
        compareBtn.setOnClickListener(this);

        progressBar = (ProgressBar) findViewById(R.id.progress);
        resultView = (TextView) findViewById(R.id.result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_local:
                photoDirection = PHOTO_LEFT;
                // 本地图片
                Intent leftLocalIntent = new Intent(Intent.ACTION_PICK, null);
                leftLocalIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(leftLocalIntent, PHOTO_REQUEST_GALLERY);

                break;
            case R.id.left_take:
                photoDirection = PHOTO_LEFT;

                if (tempFile == null) {
                    new File(getExternalStorageDirectory(), "temp.jpg");
                }
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                // 调用系统的拍照功能
                Intent leftTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            FileProvider.getUriForFile(CompareActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile));
                } else {
                    // 指定调用相机拍照后照片的储存路径
                    leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(tempFile));
                }
                startActivityForResult(leftTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                break;
            case R.id.right_local:
                photoDirection = PHOTO_RIGHT;
                // 本地图片
                Intent rightLocalIntent = new Intent(Intent.ACTION_PICK, null);
                rightLocalIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(rightLocalIntent, PHOTO_REQUEST_GALLERY);
                break;
            case R.id.right_take:
                photoDirection = PHOTO_RIGHT;
                if (tempFile == null) {
                    new File(getExternalStorageDirectory(), "temp.jpg");
                }
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                // 调用系统的拍照功能
                Intent rightTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    if (rightTakeIntent.resolveActivity(getPackageManager()) != null) {
                        rightTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                FileProvider.getUriForFile(CompareActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile));
                        startActivityForResult(rightTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                    }

                } else {
                    // 指定调用相机拍照后照片的储存路径
                    rightTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(tempFile));
                    startActivityForResult(rightTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                }

                break;
            case R.id.compare:
                resultView.setText("");
                Bitmap bmp=leftPhoto;
                long startTime = System.currentTimeMillis(); //起始时间

                //detect face return face rect(x,y,width,height) in picture
                FaceModel[] faceModel=application.detectFaces(bmp);
                long endTime = System.currentTimeMillis(); //结束时间
                long runTime = endTime - startTime;
                Log.i("test", String.format("人脸检查方法使用时间 %d ms", runTime));
                int faceNum = 0;
                if (faceModel!=null)
                {
                    faceNum=faceModel.length;
                    FaceFeaturePoint[] points = application.detectedFacePoints(bmp,faceModel[0]);
//                    if (points!=null)
//                    {
//                        Log.i("wisMobile","no face");
//                    }
                }
                if (faceNum==0)
                {
                    Log.i("wisMobile","no face");
                    resultView.setText("无法检测到第1张照片人脸");
                    break;

                }
                if (faceNum>0)
                {

//                    FaceFeaturePoint[] points= application.detectedFacePoints(bmp,faceModel[0]);

                    startTime = System.currentTimeMillis();
                    //只提取第一个人脸的特征码
                    float[] fea = application.extractFeature(bmp,faceModel[0]);
                    endTime = System.currentTimeMillis(); //结束时间
                    Bitmap bmp2=rightPhoto;
                    FaceModel[] faceModel2=application.detectFaces(bmp2);
                    runTime = endTime - startTime;
                    Log.i("test", String.format("方法使用时间 %d ms", runTime));
                    if (faceModel2==null)
                    {
                        Log.i("wisMobile","no face");
                        resultView.setText("无法检测到第2张照片人脸");
                        break;
                    }

                    faceNum=faceModel2.length;
                    if (faceNum>0)
                    {
                        Log.i("wisMobile", "detectFace size=" + faceNum + ",rect(x,y,width,height) = " + faceModel2[0].rtFace.x + "," + faceModel2[0].rtFace.y
                                + "," + faceModel2[0].rtFace.width + "," + faceModel2[0].rtFace.height);

                        float[] fea2 = application.extractFeature(bmp2,faceModel2[0]);

                        //calculate two face feature similarity(0,1)
                        score = application.face2Face(fea,fea2);
                        float score2 = application.face2FaceV2(fea,fea2);
//                        resultView.setText(Double.toString(score));
//                        progressBar.setVisibility(View.VISIBLE);

//                        Message msg = new Message();
//                        msg.what = (int)(score*100);
//                        mHandler.sendMessage(msg);
                        Log.i("wisMobile","Face score="+score);
                        resultView.setText("相似度:"+score*100+"%");
                    }
                    else
                    {
                        resultView.setText("无法检测到第2张照片人脸");
                    }

                }
                else
                {
                    resultView.setText("无法检测到第1张照片人脸");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:
                if (tempFile == null) return;
                Uri imageUri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    //通过FileProvider创建一个content类型的Uri
                    imageUri = FileProvider.getUriForFile(CompareActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
//            outputUri = Uri.fromFile(new File(crop_image));
                    //TODO:outputUri不需要ContentUri,否则失败
                    //outputUri = FileProvider.getUriForFile(activity, "com.solux.furniture.fileprovider", new File(crop_image));
                } else {
                    imageUri = Uri.fromFile(tempFile);
//            outputUri = Uri.fromFile(new File(crop_image));
                }
                startPhotoZoom(imageUri, 150);
                break;
            case PHOTO_REQUEST_GALLERY:
                if (data != null)
                    startPhotoZoom(data.getData(), 150);
                break;
            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startPhotoZoom(Uri uri, int size) {
        File CropPhoto = new File(getExternalCacheDir(), "Crop.jpg");//这个是创建一个截取后的图片路径和名称。
        try {
            if (CropPhoto.exists()) {
                CropPhoto.delete();
            }
            CropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        uritempFile = Uri.fromFile(CropPhoto);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高

        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);

        intent.putExtra("return-data", false);
        uritempFile = Uri.parse("file://" + "/" + getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    // 将进行剪裁后的图片显示到UI界面上
    @SuppressWarnings("deprecation")
    private void setPicToView(Intent picdata) {
        Bitmap bitmap = null;
        if (uritempFile!=null)
        {
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }


        if (bitmap != null) {

            // 更新UI
            Drawable drawable = new BitmapDrawable(bitmap);
            switch (photoDirection) {
                case PHOTO_LEFT:
                    leftPhoto=bitmap;
                    leftImageView.setBackgroundDrawable(drawable);
                    break;
                case PHOTO_RIGHT:
                    rightPhoto=bitmap;
                    rightImageView.setBackgroundDrawable(drawable);
                    break;
            }
            // 保存Bitmap到本地
//            saveBitmap(photo);
        }
    }

    private void saveBitmap(Bitmap bmp) {
        File file = new File("/sdcard/wis/images");
        if (!file.exists()) {
            file.mkdirs();
        }
        switch (photoDirection) {
            case PHOTO_LEFT:
                file = new File("/sdcard/wis/images/1.jpg");
                break;
            case PHOTO_RIGHT:
                file = new File("/sdcard/wis/images/2.jpg");
                break;
        }

        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
            new SingleMediaScanner(this, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getPhotoFileName() {
        return "temp.jpg";
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }

}
